package com.groupbuying.sysconfig.utils;

import com.groupbuying.sysconfig.dto.AreaDTO;
import com.groupbuying.sysconfig.dto.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * class_name: TreeBuilder
 * package: com.groupbuying.sysconfig.utils
 * description: 提供静态方法用于递归的构建树结构和递归查找子节点
 * creat_user: Ywxd
 * creat_date: 2019/3/14
 * creat_time: 15:14
 **/
public class TreeBuilder {

    /**
     * 使用递归方法建树
     * @param treeNodes
     * @return
     */
    public static List<TreeNode> buildByRecursive(List<TreeNode> treeNodes) {
        List<TreeNode> trees = new ArrayList<TreeNode>();
        for (TreeNode treeNode : treeNodes) {
            if ("-1".equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     * @return
     */
    public static List<AreaDTO> areaBuildByRecursive(List<AreaDTO> areaDTOS) {
        List<AreaDTO> trees = new ArrayList<AreaDTO>();
        for (AreaDTO areaDTO : areaDTOS) {
            if ("-1".equals(areaDTO.getParentId())) {
                trees.add(areaFindChildren(areaDTO,areaDTOS));
            }
        }
        return trees;
    }


    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static TreeNode findChildren(TreeNode treeNode,List<TreeNode> treeNodes) {
        for (TreeNode it : treeNodes) {
            if(treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static AreaDTO areaFindChildren(AreaDTO treeNode,List<AreaDTO> treeNodes) {
        for (AreaDTO it : treeNodes) {
            if(treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<AreaDTO>());
                }
                treeNode.getChildren().add(areaFindChildren(it,treeNodes));
            }
        }
        return treeNode;
    }

}
